package controllers

import (
	"encoding/json"
	"system_go/models"
	"system_go/pkg/app"
	"system_go/pkg/e"
	"system_go/services"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func Get_Spends(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	searchName := ""
	if arg := c.Query("searchName"); arg != "" {
		searchName = arg
	}
	supplierParam := map[string]interface{}{
		"page":       page,
		"limit":      limit,
		"searchName": searchName,
	}
	err, info, total := services.GetAllSpends(supplierParam)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}

func Add_Spends(c *gin.Context) {
	var m map[string]string
	b, _ := c.GetRawData()
	_ = json.Unmarshal(b, &m)
	specomid := m["specomid"]
	spepetid := m["spepetid"]
	spenum := com.StrTo(m["spenum"]).MustInt()
	speunit := com.StrTo(m["speunit"]).MustInt()
	spetotal := com.StrTo(m["spetotal"]).MustInt()

	err := services.AddSpends(models.Spend{specomid, spepetid, spenum, speunit, spetotal})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "添加成功")
}

func Update_Spends(c *gin.Context) {
	var m map[string]string
	b, _ := c.GetRawData()
	_ = json.Unmarshal(b, &m)
	specomid := m["specomid"]
	spepetid := m["spepetid"]
	spenum := com.StrTo(m["spenum"]).MustInt()
	speunit := com.StrTo(m["speunit"]).MustInt()
	spetotal := com.StrTo(m["spetotal"]).MustInt()

	err := services.UpdateSpends(models.Spend{specomid, spepetid, spenum, speunit, spetotal})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "更新成功")
}

func Del_Spends(c *gin.Context) {
	code := c.Query("spepetid")
	err := services.DelSpends(code)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "删除成功")
}
